#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
消息服务

职责：
- 实现消息相关的业务逻辑
- 调用DAO层进行数据操作
- 不直接处理HTTP请求或响应
"""

import sys
import os
import threading
import time
import logging
from typing import List, Dict, Any, Optional

from models import Belong

# 添加pywechat路径到系统路径
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'utils', 'pywechat'))

from services.app_service import AppService
from services.wechat_api_service import WechatAPIService
# 确保从正确的路径导入
import dao.wechat_dao
import dao.message_dao
import dao.account_dao

# 使用完整的类引用
WechatDAO = dao.wechat_dao.WechatDAO
MessageDAO = dao.message_dao.MessageDAO
AccountDAO = dao.account_dao.AccountDAO

class MessageService:
    """
    消息服务类
    负责处理所有消息相关的业务逻辑
    """
    
    def __init__(self):
        self.app_service = AppService()
        self.wechat_dao = WechatDAO()
        self.message_dao = MessageDAO()
        self.account_dao = AccountDAO()
        self.wechat_api_service = WechatAPIService()
        self.logger = logging.getLogger(__name__)
        self.monitoring: dict = {}
        self.monitor_thread = None
        self.auto_reply_message = "恭喜发财"  # 默认自动回复消息
        self.start_time = None
        self.processed_count = 0
        self.reply_count = 0
    
    def send_message(self,account_id: str, target: str, message: str, target_type: str = 'friend') -> Dict[str, Any]:
        """
        发送消息
        
        Args:
            account_id （str）： 当前账户归属
            target (str): 目标用户或群组
            message (str): 消息内容
            target_type (str): 目标类型（friend/group）
            
        Returns:
            dict: 处理结果
        """
        try:
            # 检查应用实例
            app_instance = self.app_service.get_app_instance()
            if not app_instance:
                return {
                    "success": False,
                    "error": "微信后端应用未初始化",
                    "status_code": 500
                }
            
            # 调用微信API发送消息
            try:
                if target_type == 'friend':
                    message_id = self.wechat_api_service.send_message_to_friend(account_id,target.strip(), message.strip())

                elif target_type == 'group':
                    message_id = self.wechat_api_service.send_message_to_group(account_id, target.strip(), message.strip())
                else:
                    return {
                        "success": False,
                        "error": f"不支持的目标类型: {target_type}",
                        "status_code": 400
                    }
                self.logger.info(f"消息发送API调用结果: 成功！ 信息ID：{message_id}")

            except Exception as e:
                self.logger.error(f"调用微信API发送消息失败: {e}")
                return {
                    "success": False,
                    "error": f"调用微信API发送消息失败: {e}",
                    "status_code": 500
                }
            return {
                    "success": True,
                    "message": f"消息已发送到 {target.strip()}",
                    "message_id": message_id
                }
        except Exception as e:
            self.logger.error(f"发送消息处理失败: {e}")
            return {
                "success": False,
                "error": str(e),
                "status_code": 500
            }

    #todo 想写啥忘记了
    def send_messages_by_id(self, ids: List[str], messages: List[str], target_type: str = 'friend') -> Dict[str, Any]:
        """
        通过ID批量发送消息

        Args:
            ids (list[str]): 目标用户的ID列表
            messages (list[str]): 待发送的消息列表
            target_type (str): 目标类型（friend/group）

        Returns:
            dict: 处理结果
        """

        # 校验数据，尤其是ID和消息
        if not all(isinstance(message, str) for message in messages) or not all(isinstance(id, str) for id in ids):
            return {}
        # 调用接口 ，先查询用户的ID，需要返回用户的昵称，然后将消息发送到对应的用户
    
    def start_monitoring(self,account_id: str, duration: str = "1h") -> Dict[str, Any]:

        """
        启动消息监控
        
        Args:
            account_id (str): 当前用户账号

            duration (str): 监控持续时间
            
        Returns:
            dict: 处理结果
        """
        try:
            # 检查监控状态
            if self.monitoring.get(account_id):

                return {
                    "success": False,
                    "error": "消息监控已在运行中",
                    "status_code": 400
                }
            
            # 验证持续时间格式
            if not self._validate_duration_format(duration):
                return {
                    "success": False,
                    "error": "持续时间格式无效，支持格式：1s, 30min, 2h",
                    "status_code": 400
                }

            # 校验账号是否存在
            owner = self.wechat_dao.get_account_info(account_id)
            if not owner:
                return {
                    "success": False,
                    "error": "账号不存在",
                    "status_code": 400
                }

            
            # 启动监控 未来可以放在redis中
            self.monitoring[account_id] = owner

            self.start_time = time.time()
            self.processed_count = 0
            self.reply_count = 0
            
            self.monitor_thread = threading.Thread(
                target=self._monitor_messages,
                args=(owner,duration),
                daemon=True
            )
            self.monitor_thread.start()
            
            self.logger.info(f"消息监控已启动，持续时间: {duration}")
            return {
                "success": True,
                "message": f"消息监控已启动，持续时间: {duration}"
            }
            
        except Exception as e:
            self.logger.error(f"启动消息监控处理失败: {e}")
            if account_id in self.monitoring:
                del self.monitoring[account_id]
            return {
                "success": False,
                "error": str(e),
                "status_code": 500
            }
    
    def stop_monitoring(self, account_id: str = None) -> Dict[str, Any]:
        """
        停止消息监控
        
        Args:
            account_id (str, optional): 账号ID，如果为None则停止所有监控
            
        Returns:
            dict: 处理结果
        """
        try:
            # 检查监控状态
            if not self.monitoring:
                return {
                    "success": False,
                    "error": "消息监控未在运行",
                    "status_code": 400
                }
            
            # 停止监控
            if account_id is not None:
                if account_id not in self.monitoring:
                    return {
                        "success": False,
                        "error": f"账号 {account_id} 的消息监控未在运行",
                        "status_code": 400
                    }
                del self.monitoring[account_id]
            else:
                self.monitoring.clear()
                
            if self.monitor_thread and self.monitor_thread.is_alive():
                self.monitor_thread.join(timeout=5)
            
            self.logger.info("消息监控已停止")
            return {
                "success": True,
                "message": "消息监控已停止"
            }
            
        except Exception as e:
            self.logger.error(f"停止消息监控处理失败: {e}")
            return {
                "success": False,
                "error": str(e),
                "status_code": 500
            }
    
    def get_monitoring_status(self, account_id: str = None) -> Dict[str, Any]:
        """
        获取监控状态
        
        Args:
            account_id (str, optional): 账号ID，如果为None则获取所有监控状态
            
        Returns:
            dict: 监控状态信息
        """
        try:
            # 计算运行时间
            running_duration = 0
            if self.start_time:
                running_duration = int(time.time() - self.start_time)
                
            is_monitoring = False
            if account_id is not None:
                is_monitoring = account_id in self.monitoring
            else:
                is_monitoring = bool(self.monitoring)
            
            return {
                "success": True,
                "data": {
                    "monitoring": is_monitoring,
                    "auto_reply_message": self.auto_reply_message,
                    "thread_alive": self.monitor_thread.is_alive() if self.monitor_thread else False,
                    "start_time": self.start_time,
                    "running_duration": running_duration,
                    "processed_count": self.processed_count,
                    "reply_count": self.reply_count
                }
            }
        except Exception as e:
            self.logger.error(f"获取监控状态处理失败: {e}")
            return {
                "success": False,
                "error": str(e),
                "status_code": 500
            }
    
    def set_auto_reply_message(self, message: str) -> Dict[str, Any]:
        """
        设置自动回复消息
        
        Args:
            message (str): 自动回复消息内容
            
        Returns:
            dict: 处理结果
        """
        try:
            # 验证消息内容
            if not message or not message.strip():
                return {
                    "success": False,
                    "error": "回复消息不能为空",
                    "status_code": 400
                }
            
            # 验证消息长度
            if len(message.strip()) > 500:
                return {
                    "success": False,
                    "error": "回复消息长度不能超过500字符",
                    "status_code": 400
                }
            
            # 设置自动回复消息
            self.auto_reply_message = message.strip()
            self.logger.info(f"自动回复消息已设置为: {self.auto_reply_message}")
            
            return {
                "success": True,
                "message": f"自动回复消息已设置为: {self.auto_reply_message}"
            }
            
        except Exception as e:
            self.logger.error(f"设置自动回复消息处理失败: {e}")
            return {
                "success": False,
                "error": str(e),
                "status_code": 500
            }
    
    def _validate_duration_format(self, duration: str) -> bool:
        """
        验证持续时间格式的业务逻辑
        
        Args:
            duration (str): 持续时间字符串
            
        Returns:
            bool: 格式是否有效
        """
        import re
        pattern = r'^\d+[smh]$|^\d+min$'
        return bool(re.match(pattern, duration.lower()))
    
    def _monitor_messages(self, owner: Belong, duration: str):
        """
        消息监控主循环
        
        Args:
            owner (Belong): 账号所有者信息
            duration (str): 监控持续时间
        """
        try:
            account_id = owner.id if owner and hasattr(owner, 'id') else None
            if not account_id:
                self.logger.error("无法获取账号ID，无法启动监控")
                return
                
            self.logger.info(f"开始监控微信消息，账号ID: {account_id}，持续时间: {duration}")
            
            # 监控持续时间处理
            end_time = None
            if duration:
                # 解析持续时间
                unit = duration[-1].lower()
                if unit == 'n' and duration.lower().endswith('min'):
                    unit = 'm'
                    value = int(duration[:-3])
                else:
                    value = int(duration[:-1])
                
                # 计算结束时间
                if unit == 's':
                    end_time = time.time() + value
                elif unit == 'm':
                    end_time = time.time() + value * 60
                elif unit == 'h':
                    end_time = time.time() + value * 3600
            
            while account_id in self.monitoring:
                # 检查是否超过持续时间
                if end_time and time.time() > end_time:
                    self.logger.info(f"监控时间已到，停止监控，账号ID: {account_id}")
                    break
                    
                try:
                    # 检查新消息（通过微信API服务）
                    new_messages = self.wechat_api_service.check_new_messages("10s")
                    
                    if new_messages:
                        self.logger.info(f"检测到 {len(new_messages)} 条新消息")
                        self.processed_count += len(new_messages)
                        
                        # 处理每条新消息
                        for message_info in new_messages:
                            if self._process_new_message(message_info):
                                self.reply_count += 1
                    
                    # 休眠间隔
                    time.sleep(10)
                    
                except Exception as e:
                    self.logger.error(f"监控消息处理时发生错误: {e}")
                    time.sleep(5)
                    
        except Exception as e:
            self.logger.error(f"消息监控线程异常: {e}")
        finally:
            if account_id in self.monitoring:
                del self.monitoring[account_id]
            self.logger.info(f"消息监控已结束，账号ID: {account_id}")
    
    def _process_new_message(self, message_info: Dict[str, Any]) -> bool:
        """
        处理新消息并自动回复
        
        Args:
            message_info (dict): 消息信息
            
        Returns:
            bool: 是否成功回复
        """
        try:
            friend_name = message_info.get('好友名称', '')
            friend_type = message_info.get('好友类型', '')
            message_count = message_info.get('新消息条数', 0)
            message_contents = message_info.get('消息内容', [])
            
            self.logger.info(f"处理来自 {friend_name}({friend_type}) 的 {message_count} 条新消息")
            
            # 记录消息内容
            for i, content in enumerate(message_contents):
                self.logger.info(f"消息 {i+1}: {content}")
                # 保存接收到的消息记录到数据库
                message_record = {
                    'sender': friend_name,
                    'receiver': 'self',
                    'content': content,
                    'message_type': 'text',
                    'direction': 'received',
                    'status': 'success'
                }
                
                try:
                    message_id = self.message_dao.save_message(message_record)
                    self.logger.info(f"接收消息记录已保存，ID: {message_id}")
                except Exception as save_err:
                    self.logger.error(f"保存接收消息记录失败: {save_err}")
            
            # 判断是否需要自动回复
            if friend_name and friend_type in ['好友', '群聊'] and self.auto_reply_message:
                try:
                    # 调用微信API服务发送自动回复
                    success = self.wechat_api_service.send_message_to_friend(friend_name, self.auto_reply_message)
                    if success:
                        self.logger.info(f"已向 {friend_name} 自动回复: {self.auto_reply_message}")
                        # 保存自动回复记录到数据库
                        auto_reply_data = {
                            'sender': 'self',
                            'receiver': friend_name,
                            'original_content': message_contents[-1] if message_contents else '',
                            'reply_content': self.auto_reply_message,
                            'message_type': 'text'
                        }
                        
                        try:
                            message_id = self.message_dao.save_auto_reply(auto_reply_data)
                            self.logger.info(f"自动回复记录已保存，ID: {message_id}")
                        except Exception as save_err:
                            self.logger.error(f"保存自动回复记录失败: {save_err}")
                    else:
                        self.logger.error(f"向 {friend_name} 发送自动回复失败")
                    
                    if success:
                        return True
                    else:
                        self.logger.error(f"向 {friend_name} 自动回复失败")
                        return False
                        
                except Exception as e:
                    self.logger.error(f"向 {friend_name} 自动回复失败: {e}")
                    return False
            
            return False
            
        except Exception as e:
            self.logger.error(f"处理新消息时发生错误: {e}")
            return False